package com.sanxia.market.Scheduled;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.sanxia.common.utils.HttpClientUtil;
import com.sanxia.common.utils.JsonUtil;
import com.sanxia.market.entity.WxInfo;
import com.sanxia.market.service.WxInfoService;



/**
 * 定时任务，定时请求微信接口获取access_token，并更新至数据库
 * @author vagun
 *
 */
@Component
public class ScheduledTasks implements CommandLineRunner {

	private final  Logger logger = (Logger) LoggerFactory.getLogger(ScheduledTasks.class);

	private static final long ScheduledTasksTime = 110*60*1000;//定时任务执行间隔时间

	@Autowired
	private WxInfoService wxInfoService;

	/**
	 * 项目启动时执行一次
	 */
	@Override
	public void run(String... args) throws Exception {
		logger.info("项目启动时执行一次,获取AccessToken");
	//	initAccessToken();
	}

	/**
	 * 每隔相应时间执行一次
	 */
    @Scheduled(fixedDelay = ScheduledTasksTime)
    public void reportCurrentTime() {
    	logger.info("每隔相应时间执行一次,获取AccessToken");
    	initAccessToken();
    }

    /**
     * 初始化AccessToken
     */
    private void initAccessToken() {
    	logger.info("方法：initAccessToken()");
    	//由于目前只有头号玩家有此需求，所以只跑视小宝公众号的信息
    	Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("mchId", "2");
		WxInfo	wxInfo=wxInfoService.getBy(paramMap);


    	String accurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
		String appid=wxInfo.getWxAppid();
		String 	appsecret=	wxInfo.getWxAppSecret();
		String requestUrl = accurl.replace("APPID", appid).replace(
	            "APPSECRET", appsecret);

		String jsonString =HttpClientUtil.doGet(requestUrl);
		Map<String,Object> maprest=JsonUtil.jsonStr2Map(jsonString);
		//{"access_token":"22_eFicwu308DMmneLalsGXbykS5yDhGQ2tDJ1fKqWuQ7ho5usi7SdIC0243GpcMEQOn6b6Xpng-c4XQa8zxRQ8KcamBxOM7kv-VM0Lu5iGrLVXsQSVdeHsHnzoAeMb105jssDTKjIwBhVLvAJSYNEeAAAGVM","expires_in":7200}

		String  api="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		String access_token=maprest.get("access_token")+"";
		String apiurl=api.replace("ACCESS_TOKEN", access_token);
		String apijsonString =HttpClientUtil.doGet(apiurl);
		Map<String,Object> apimaprest=JsonUtil.jsonStr2Map(apijsonString);
		String ticket=apimaprest.get("ticket")+"";
		wxInfo.setAccessToken(access_token);
		wxInfo.setJsapiTicket(ticket);
		wxInfoService.updateOne(wxInfo);
	//{"errcode":0,"errmsg":"ok","ticket":"LIKLckvwlJT9cWIhEQTwfIiEX_Jq-w7Rs3cTWx2QYIhA6hCcCur1ism_FTUrYiRPgJId8SqSg9YVeyNMM62RhA","expires_in":7200}


    }
}
